from django.core.management.base import BaseCommand
from django.contrib.auth import get_user_model
from accounts.models import Institution, Laboratory

User = get_user_model()


class Command(BaseCommand):
    help = '创建测试用户'

    def handle(self, *args, **options):
        # 获取机构和实验室
        try:
            cau = Institution.objects.get(code='CAU')
            sasl = Laboratory.objects.get(code='SASL', institution=cau)
            pdrl = Laboratory.objects.get(code='PDRL', institution=cau)
            other_inst = Institution.objects.get(code='OTHER')
            other_lab = Laboratory.objects.get(code='OTHER', institution=other_inst)
        except (Institution.DoesNotExist, Laboratory.DoesNotExist) as e:
            self.stdout.write(
                self.style.ERROR(f'机构或实验室不存在，请先运行数据库初始化脚本: {e}')
            )
            return

        # 创建测试用户
        users_data = [
            {
                'username': 'member_test',
                'email': 'member@test.com',
                'password': '123456',
                'full_name': '测试成员',
                'phone': '13800038000',
                'institution': cau,
                'laboratory': sasl,
                'user_type': 'member',
                'is_staff': False,
                'is_superuser': False,
            },
            {
                'username': 'lab_admin',
                'email': 'lab@test.com',
                'password': '123456',
                'full_name': '实验室管理员',
                'phone': '13900139000',
                'institution': cau,
                'laboratory': pdrl,
                'user_type': 'laboratory',
                'is_staff': True,
                'is_superuser': False,
            },
            {
                'username': 'admin',
                'email': 'admin@system.com',
                'password': 'admin123456',
                'full_name': '系统管理员',
                'phone': '13700137000',
                'institution': other_inst,
                'laboratory': other_lab,
                'user_type': 'laboratory',
                'is_staff': True,
                'is_superuser': True,
            }
        ]

        for user_data in users_data:
            email = user_data['email']
            if not User.objects.filter(email=email).exists():
                password = user_data.pop('password')
                user = User.objects.create_user(**user_data)
                user.set_password(password)
                user.save()
                self.stdout.write(
                    self.style.SUCCESS(f'成功创建用户: {email}')
                )
            else:
                self.stdout.write(
                    self.style.WARNING(f'用户已存在: {email}')
                )

        self.stdout.write(
            self.style.SUCCESS('测试用户创建完成！')
        )